//
//  AlarmMessageViewController.m
//  SIPphone
//
//  Created by wrt on 14-2-17.
//  Copyright (c) 2014年 wrtsoft. All rights reserved.
//

#import "AlarmMessageViewController.h"
#import "AlarmDataBase.h"
#import "AlarmMessageCell.h"
#import "AlarmMessage.h"
#import "AlarmMessageDetailViewController.h"

@interface AlarmMessageViewController ()
@property (assign, nonatomic) int begin;
@end

@implementation AlarmMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"alarm message", @"报警消息 Alarm message");
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.begin = 0;
    // Do any additional setup after loading the view from its nib.
    AlarmDataBase *alarmDB =[AlarmDataBase shareAlarmDataBase];
    [alarmDB readDB];
    [alarmDB readDBForpartWithBeginNumber:self.begin];
    
    self.alarmUriArray = [[NSMutableArray alloc] init];
    self.publishArray = [[NSMutableArray alloc] init];
    self.startTimeArray = [[NSMutableArray alloc] init];
    self.endTimeArray = [[NSMutableArray alloc] init];
    self.resultArray = [[NSMutableArray alloc] init];
    self.remarkArray = [[NSMutableArray alloc] init];
    self.tomanagerArray = [[NSMutableArray alloc] init];
    self.alarmTypeArray = [[NSMutableArray alloc] init];
    self.alarmStatusArray = [[NSMutableArray alloc] init];
    self.alarmReceiveTimeArray = [[NSMutableArray alloc] init];
    
    [self.alarmUriArray addObjectsFromArray:alarmDB.partAlarmUriArray];
    [self.publishArray addObjectsFromArray:alarmDB.partPublishUriArray];
    [self.startTimeArray addObjectsFromArray:alarmDB.partStartTimeArray];
    [self.endTimeArray addObjectsFromArray:alarmDB.partEndTimeArray];
    [self.resultArray addObjectsFromArray:alarmDB.partResultArray];
    [self.remarkArray addObjectsFromArray:alarmDB.partRemarkArray];
    [self.tomanagerArray addObjectsFromArray:alarmDB.partTomanagerArray];
    [self.alarmTypeArray addObjectsFromArray:alarmDB.partAlarmTypeArray];
    [self.alarmStatusArray addObjectsFromArray:alarmDB.partAlarmStatusArray];
    [self.alarmReceiveTimeArray addObjectsFromArray:alarmDB.partAlarmReceiveTimeArray];
    
    //删除编辑按钮
    UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"editor", @"编辑 Editor") style:UIBarButtonItemStyleBordered target:self action:@selector(deleteButtonPressed)];
    self.navigationItem.rightBarButtonItem = deleteButton;
    
    //设置通知来刷新界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadtableView:) name:@"RELOADTABLEVIEWALARMMSG" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//编辑按钮操作
- (void)deleteButtonPressed
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"取消 cancel") destructiveButtonTitle:NSLocalizedString(@"clear All Records", @"清除全部记录 Clear All Records") otherButtonTitles:NSLocalizedString(@"clear single record", @"清除单个记录 Clear single record"), nil];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow]; //这么加进去就不会“取消”按钮按了没反应
}

#pragma mark -
#pragma mark tableViewDelegateMethod
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.startTimeArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlarmMessageCell *cell;
    //此处的identifier必须要和自定义的cell的xib中identifier一致，否则无法重用
    static NSString *identifier = @"AlarmMessageCell";
    cell = (AlarmMessageCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        //将自定义cell中的所有xib对象载入
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AlarmMessageCell" owner:nil options:nil];
        cell = [nib objectAtIndex:0];
    }
    //修改自定义cell的xib中的控件
    cell.alarmImageView.image = [UIImage imageNamed:@"xiaoxi_chenggong.png"];
    cell.alarmUriLabel.text = self.alarmUriArray[indexPath.row];
    
    //判断是什么事件然后显示
    switch ([self.alarmTypeArray[indexPath.row] integerValue])
    {
//        case 0:
//            cell.alarmUriLabel.text = @"无事件";
//            break;
        case 1:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"fire", @"火灾 Fire"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"huozaibaojing.png"];
            break;
        case 2:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"gas", @"瓦斯 Gas"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"wasibaojing.png"];
            break;
        case 3:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"infrared", @"红外线 Infrared"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"hongwaixian.png"];
            break;
        case 4:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"magnetic", @"门磁 Magnetic"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"mencibaojing.png"];
            break;
        case 5:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"zone5", @"防区5 Zone 5"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"fangqu5.png"];
            break;
        case 6:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"zone6", @"防区6 Zone 6"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"fangqu6.png"];
            break;
        case 7:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"zone7", @"防区7 Zone 7"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"fangqu7.png"];
            break;
        case 8:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"zone8", @"防区8 Zone 8"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"fangqu8.png"];
            break;
        case 9:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"tamper", @"防拆 Tamper"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"fanchaibaojing.png"];
            break;
        case 10:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"illegaldoor", @"非法开门 Illegal door"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"feifakaimenbaojing.png"];
            break;
        case 11:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"stressdoor", @"胁迫开门 Stress door"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"xiepokaimenbaojing.png"];
            break;
        case 12:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"hostMagnetic", @"主机门磁 Host Magnetic"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"zhujimenci.png"];
            break;
        case 13:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"undervoltage", @"欠压 Undervoltage"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"qianyabaojing.png"];
            break;
        case 14:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"voltage returns to normal", @"电压恢复正常 Voltage returns to normal")];
            cell.imageView.image = [UIImage imageNamed:@"dianyahuifuzhengchang.png"];
            break;
        case 15:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"arming", @"布防 Arming"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"bufang.png"];
            break;
        case 16:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"disarming", @"撤防 Disarming"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            break;
            cell.imageView.image = [UIImage imageNamed:@"chefang.png"];
        case 17:
            cell.alarmTypeLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"batch", @"批处理 Batch"),NSLocalizedString(@"alarm", @"报警 Alarm")];
            cell.imageView.image = [UIImage imageNamed:@"pichuli.png"];
            break;
        default:
            break;
    }
    
    cell.alarmTimeLabel.text = self.alarmReceiveTimeArray[indexPath.row];
    
    //根据未读已读改变字体的颜色
    [cell changColorWithIsRead:1];
    if ([self.alarmStatusArray[indexPath.row] isEqualToString:@"未读"])
    {
        [cell changColorWithIsRead:0];
    }
    else
    {
        [cell changColorWithIsRead:1];
    }
    
    cell.tag = indexPath.row + 1;
    
    return cell;
}

//cell选择后的处理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlarmDataBase *alarmDB = [AlarmDataBase shareAlarmDataBase];
    
    
    //获取选择的cell是哪一个
    AlarmMessageCell *cell = (AlarmMessageCell *)[self.view viewWithTag:(indexPath.row + 1)];
    [cell changColorWithIsRead:1];
    //若是未读状态 则将其对应数据库里面的状态改成“已读”
    if ([self.alarmStatusArray[indexPath.row] isEqualToString:@"未读"])
    {
        [alarmDB editStatusWithStartTime:self.startTimeArray[indexPath.row] andAlarmUri:self.alarmUriArray[indexPath.row] andAlarmtype:[self.alarmTypeArray[indexPath.row] intValue]];
        [self.alarmStatusArray  replaceObjectAtIndex:indexPath.row withObject:@"已读"];
    }
    
    AlarmMessageDetailViewController *alarmMsgDetailVC = [[AlarmMessageDetailViewController alloc] initWithAlarmType:[self.alarmTypeArray[indexPath.row] intValue] andAlarmURI:self.alarmUriArray[indexPath.row] andPublishURI:self.publishArray[indexPath.row] andStartTime:self.startTimeArray[indexPath.row] andEndTime:self.endTimeArray[indexPath.row] andResult:self.resultArray[indexPath.row] andRemark:self.remarkArray[indexPath.row] andTomanager:[self.tomanagerArray[indexPath.row] intValue]];
    [self.navigationController pushViewController:alarmMsgDetailVC animated:YES];
}

//编辑模式下可删除的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //数据库执行删除
    AlarmDataBase *alarmDB = [AlarmDataBase shareAlarmDataBase];
    [alarmDB deleteWithStartTime:self.startTimeArray[indexPath.row] andAlarmUri:self.alarmUriArray[indexPath.row] andAlarmtype:[self.alarmTypeArray[indexPath.row] intValue]];
    
    
    //删除掉对应数组内的内容
    [self.alarmUriArray removeObjectAtIndex:indexPath.row];
    [self.publishArray removeObjectAtIndex:indexPath.row];
    [self.startTimeArray removeObjectAtIndex:indexPath.row];
    [self.endTimeArray removeObjectAtIndex:indexPath.row];
    [self.resultArray removeObjectAtIndex:indexPath.row];
    [self.remarkArray removeObjectAtIndex:indexPath.row];
    [self.tomanagerArray removeObjectAtIndex:indexPath.row];
    [self.alarmTypeArray removeObjectAtIndex:indexPath.row];
    [self.alarmStatusArray removeObjectAtIndex:indexPath.row];
    [self.alarmReceiveTimeArray removeObjectAtIndex:indexPath.row];
    
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark -
#pragma mark actionSheetMethod
//UIActionSheet 对应按钮的操作
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //数据库执行删除
        AlarmDataBase *alarmDB = [AlarmDataBase shareAlarmDataBase];
        [alarmDB removeAlldata];
        //删除掉对应数组内的内容
        [self.alarmUriArray removeAllObjects];
        [self.publishArray removeAllObjects];
        [self.startTimeArray removeAllObjects];
        [self.endTimeArray removeAllObjects];
        [self.resultArray removeAllObjects];
        [self.remarkArray removeAllObjects];
        [self.tomanagerArray removeAllObjects];
        [self.alarmTypeArray removeAllObjects];
        [self.alarmStatusArray removeAllObjects];
        [self.alarmReceiveTimeArray removeAllObjects];
        [self.tableView reloadData];
    }
    if (buttonIndex == 1)
    {
        //进入编辑模式
        [self.tableView setEditing:!self.tableView.editing];
    }
    if (buttonIndex == 2)
    {
        
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.tableView.contentOffset.y >= self.tableView.contentSize.height - self.tableView.frame.size.height)
    {
        AlarmDataBase *alarmDB = [AlarmDataBase shareAlarmDataBase];
        self.begin = self.startTimeArray.count;
        [alarmDB readDBForpartWithBeginNumber:self.begin];
        
        [self.alarmUriArray addObjectsFromArray:alarmDB.partAlarmUriArray];
        [self.publishArray addObjectsFromArray:alarmDB.partPublishUriArray];
        [self.startTimeArray addObjectsFromArray:alarmDB.partStartTimeArray];
        [self.endTimeArray addObjectsFromArray:alarmDB.partEndTimeArray];
        [self.resultArray addObjectsFromArray:alarmDB.partResultArray];
        [self.remarkArray addObjectsFromArray:alarmDB.partRemarkArray];
        [self.tomanagerArray addObjectsFromArray:alarmDB.partTomanagerArray];
        [self.alarmTypeArray addObjectsFromArray:alarmDB.partAlarmTypeArray];
        [self.alarmStatusArray addObjectsFromArray:alarmDB.partAlarmStatusArray];
        [self.alarmReceiveTimeArray addObjectsFromArray:alarmDB.partAlarmReceiveTimeArray];
        
        [self.tableView reloadData];
    }
}

- (void)reloadtableView:(NSNotification *)notification
{
    
    dispatch_async(dispatch_get_main_queue(),^{
        
        AlarmMessage *alarmMsg = [[AlarmMessage alloc] init];
        alarmMsg = (AlarmMessage *)notification.object;
        [self.alarmUriArray insertObject:alarmMsg.alarmUri atIndex:0];
        [self.publishArray insertObject:alarmMsg.publishUri atIndex:0];
        [self.startTimeArray insertObject:alarmMsg.startTime atIndex:0];
        [self.endTimeArray insertObject:alarmMsg.endTime atIndex:0];
        [self.resultArray insertObject:alarmMsg.result atIndex:0];
        [self.remarkArray insertObject:alarmMsg.remark atIndex:0];
        [self.tomanagerArray insertObject:[NSNumber numberWithInt:alarmMsg.tomanager] atIndex:0];
        [self.alarmTypeArray insertObject:[NSNumber numberWithInt:alarmMsg.alarmType] atIndex:0];
        [self.alarmStatusArray insertObject:alarmMsg.alarmStatus atIndex:0];
        [self.alarmReceiveTimeArray insertObject:alarmMsg.receiveTime atIndex:0];
        //刷新表格
        [self.tableView reloadData];
    });
}

- (void)dealloc
{
    //取消通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RELOADTABLEVIEWALARMMSG" object:nil];
}

@end
